<?php

namespace frontend\controllers;

use frontend\models\Bank;
use frontend\models\Goods;
use frontend\models\GoodsCate;
use frontend\models\SellGoods;
use frontend\models\UserAccount;
use frontend\models\UserWithdraw;
use Yii;
use common\helpers\Curl;
use frontend\models\User;
use frontend\models\UserCoupon;
use frontend\models\Product;
use frontend\models\Order;
use frontend\models\ProductPrice;
use frontend\models\DataAll;
use frontend\models\Retail;
use frontend\models\AdminUser;
use frontend\models\UserCharge;
use common\models\ProductParam;
use common\helpers\FileHelper;
use common\helpers\Json;

class SiteController extends \frontend\components\Controller
{
    public function beforeAction($action)
    {
        if(!config('web_state', 1)) {
            return $this->redirect('/user/maintain');
        }

        $actions = ['ajax-update-status','yifunew-notify', 'wxtoken', 'wxcode', 'test', 'captcha', 'zynotify', 'login', 'register', 'forget', 'update-user', 'verify-code', 'nqdelete', 'bxnotify', 'new-bxnotify', 'klnotify', 'admin-klnotify', 'cardnotify', 'notify', 'willnotify', 'newsnotify', 'hm-alipaynotify', 'down-load', 'wxload', 'wxload-view', 'rule', 'chifunotify', 'notifys', 'pingan-notify', 'aite-notify', 'yifu-notify', 'huilong-notify'];
        if (user()->isGuest && !in_array($this->action->id, $actions)) {
            $this->redirect(['site/login']);
            return false;
            // $wx = session('wechat_userinfo');
            // if (!empty($wx)) {
            //     $user = User::find()->where(['open_id' => $wx['openid']])->one();
            //     $user->login(false);
            // } else {
            //     $code = get('code');
            //     if (empty($code)) {
            //         $this->redirect(['/wechart.php']);
            //         return false;
            //     } else {
            //         User::registerUser($code);
            //     }
            // }
        }
        if (!parent::beforeAction($action)) {
            return false;
        } else {
            return true;
        }
    }

    /***** 商城 - start ****/
    public function actionShop()
    {
        $this->view->title = '商城';
        $goods = Goods::getIndexGoods();
        return $this->render('shop', compact('goods'));
    }

    public function actionProductDetail()
    {
        $this->view->title = '商品详情';
        $id = get("id");
        if(!$id){
            $indexGoods = Goods::getIndexGoods();
            foreach ($indexGoods as $vo){
                $id = $vo->goods_id;
                break;
            }
        }
        $goods = Goods::find()->where(['state' => Goods::STATE_YES, "goods_id" => $id])->one();
        if($goods){
            return $this->render('productDetail', compact('goods'));
        }else{
            return $this->redirect(['site/wrong']);
        }
    }

    public function actionShopInformation()
    {
        $this->view->title = '商品详情';
        $goodsId = get("goods_id");
        $num = get("num", 1);
        if($goodsId && is_numeric($num) && $num > 0){
            $goods = Goods::find()->where(['state' => Goods::STATE_YES, "goods_id" => $goodsId])->one();
            if($goods){
                return $this->render('shopInformation', compact("goods", "num"));
            }else{
                return $this->redirect(['site/wrong']);
            }
        }else{
            return $this->redirect(['site/wrong']);
        }

    }

    public function actionMainHuangou()
    {
        $this->view->title = '积分商城';
        $goods = SellGoods::find()->where(['state' => SellGoods::STATE_YES])->orderBy('sort ASC')->all();
        return $this->render('mainHuangou', compact("goods"));
    }

    public function actionSellGoodsDetail()
    {
        $this->view->title = '商品详情';
        $id = get("id");
        if(!$id){
            $indexGoods = SellGoods::getIndexGoods();
            foreach ($indexGoods as $vo){
                $id = $vo->goods_id;
                break;
            }
        }
        $goods = SellGoods::find()->where(['state' => SellGoods::STATE_YES, "goods_id" => $id])->one();
        if($goods){
            return $this->render('goodsDetail', compact('goods'));
        }else{
            return $this->redirect(['site/wrong']);
        }
    }

    public function actionSaveSellOrder()
    {
        $goodsId = post("goods_id");
        $num = post("num", 1);
        if($goodsId && is_numeric($num) && $num > 0){
            $goods = SellGoods::find()->where(['state' => Goods::STATE_YES, "goods_id" => $goodsId])->one();
            if($goods){
                $userAccount = UserAccount::find()->where(['user_id' => u()->id])->one();
                if(!empty($userAccount)){
                    $totalScore = $goods->score * $num;
                    $fee = $totalScore * config('web_out_money_fee', 2) / 100;
                    if($totalScore + $fee > (u()->account - u()->blocked_account)){
                        return error("能源分不足，无法代销！");
                    }else{
                        $userWithdraw = new UserWithdraw();
                        $userWithdraw->amount = $goods->amount * $num;
                        $userWithdraw->score = $totalScore;
                        $userWithdraw->out_sn = u()->id . date("YmdHis") . rand(1000, 9999);
                        $userWithdraw->user_id = u()->id;
                        $userWithdraw->account_id = $userAccount->id;
                        $userWithdraw->goods_id = $goods->goods_id;
                        if ($userWithdraw->insert(false)) {
                            $model = User::findModel(u()->id);
                            $model->account -= $totalScore + $fee;
                            $model->save(false);
                            $url = url(['site/daixiao-record']);
                            return success($url);
                        }
                    }
                    $url = url(["site/shopInformation", "goods_id" => $goodsId, "num" => $num]);
                    return success($url);
                }else{
                    return error("请先认证资料！");
                }
            }else{
                return error("非法操作！");
            }
        }else{
            return error("非法操作！");
        }
    }

    public function actionGuide()
    {
        $this->view->title = '新手指引';
        return $this->render('guide');
    }


    public function actionPromotion()
    {
        $this->view->title = '购物商城';
        $cate = get("cate", 1);
        $goods = Goods::find()->where(['state' => Goods::STATE_YES, "cate_id" => $cate])->orderBy('sort ASC')->all();
        $cates = GoodsCate::find()->where(['state' => GoodsCate::STATE_YES])->orderBy('hot ASC')->all();
        return $this->render('promotion', compact('cate', 'goods', 'cates'));
    }

    public function actionAjaxGoodsOrder()
    {
        $goodsId = post("goods_id");
        $num = post("num", 1);
        if($goodsId && is_numeric($num) && $num > 0){
            $goods = Goods::find()->where(['state' => Goods::STATE_YES, "goods_id" => $goodsId])->one();
            if($goods){
                $url = url(["site/shopInformation", "goods_id" => $goodsId, "num" => $num]);
                return success($url);
            }else{
                return error("非法操作！");
            }
        }else{
            return error("非法操作！");
        }
    }

    public function actionGoodsPay()
    {
        $goodsId = post("goods_id");
        $num = post("num", 1);
        $type = post('type', 1);
        if($goodsId && is_numeric($num) && $num > 0){
            $goods = Goods::find()->where(['state' => Goods::STATE_YES, "goods_id" => $goodsId])->one();
            if($goods){
                $amount = $goods->amount * $num;
                $score = $goods->score * $num;
                switch ($type){
                    case '1':
                        $html = UserCharge::payAiteForGoods($amount, $score, $type, $goodsId, $num);
                        if($html){
                            return $this->render("/user/gzh", compact("html"));
                        }else{
                            return $this->redirect(['site/wrong']);
                        }
                        break;
                    case '2': // 中安微信扫码
                        $src = UserCharge::payNewZhonganForGoods($amount, $score, $type, $goodsId, $num);
                        if($src){
                            return $this->render('/user/wechat', compact('src', 'amount'));
                        }else{
                            return $this->redirect(['site/wrong']);
                        }
                        break;
                    case '3': // 中安QQ扫码
                        $src = UserCharge::payZhonganForGoods($amount, $score, $type, $goodsId, $num);
                        if($src){
                            return $this->render('/user/qqpay', compact('src', 'amount'));
                        }else{
                            return $this->redirect(['site/wrong']);
                        }
                        break;
                    case '4': // 中安QQ H5
                        $src = UserCharge::payZhonganForGoods($amount, $score, $type, $goodsId, $num);
                        if($src){
                            header("Location:$src");
                            exit();
                        }else{
                            return $this->redirect(['site/wrong']);
                        }
                        break;
                    case '5': // 中安支付宝扫码
                        $src = UserCharge::payNewZhonganForGoods($amount, $score, $type, $goodsId, $num);
                        if($src){
                            return $this->render('/user/alipay', compact('src', 'amount'));
                        }else{
                            return $this->redirect(['site/wrong']);
                        }
                        break;
                    case '6': // 中安银联扫码
                        $src = UserCharge::payNewZhonganForGoods($amount, $score, $type, $goodsId, $num);
                        if($src){
                            return $this->render('/user/unionpay', compact('src', 'amount'));
                        }else{
                            return $this->redirect(['site/wrong']);
                        }
                        break;
                    case '7': // 汇隆银联快捷
                        $html = UserCharge::payHuilongForGoods($amount, $score, $type, $goodsId, $num);
                        if($html){
                            return $this->render('/user/gzh', compact('html'));
                        }else{
                            return $this->redirect(['site/wrong']);
                        }
                        break;
                    case '8': // 汇隆QQ扫码
                        $html = UserCharge::payHuilongForGoods($amount, $score, $type, $goodsId, $num);
                        if($html){
                            return $this->render('/user/gzh', compact('html'));
                        }else{
                            return $this->redirect(['site/wrong']);
                        }
                        break;
                    case '9': // 汇隆支付宝
                        $html = UserCharge::payHuilongForGoods($amount, $score, $type, $goodsId, $num);
                        if($html){
                            return $this->render('/user/gzh', compact('html'));
                        }else{
                            return $this->redirect(['site/wrong']);
                        }
                        break;
                    case '10': // 汇隆QQ H5
                        $html = UserCharge::payHuilongForGoods($amount, $score, $type, $goodsId, $num);
                        if($html){
                            return $this->render('/user/gzh', compact('html'));
                        }else{
                            return $this->redirect(['site/wrong']);
                        }
                        break;
                    default:
                        break;
                }
            }else{
                return $this->redirect(['site/wrong']);
            }
        }else{
            return $this->redirect(['site/wrong']);
        }
    }

    public function actionDaixiaoRecord()
    {
        $this->view->title = '代销记录';
        $query = UserWithdraw::find()->where(['user_id' => u()->id])->with(['sellGoods'])->orderBy('created_at DESC');
        $data = $query->paginate(5);
        $pageCount = $query->totalCount / 5;
        if (!is_int($pageCount)) {
            $pageCount = (int)$pageCount + 1;
        }
        if (Yii::$app->request->isAjax) {
            return success($this->renderPartial('_daixiaoRecord', compact('data')), $pageCount);
        }
        return $this->render('daixiaoRecord', compact("data", "pageCount"));
    }


    public function actionTransferInt()
    {
        $this->view->title = '积分转赠';
        return $this->render('transferInt');
    }


    public function actionTransferRecord()
    {
        $this->view->title = '转赠记录';
        return $this->render('transferRecord');
    }


    public function actionMyOrder()
    {
        $this->view->title = '我的订单';
        return $this->render('myOrder');
    }

    public function actionTicket()
    {
        $this->view->title = '我的优惠券';
        return $this->render('ticket');
    }

    public function actionVerifyInfo()
    {
        $this->view->title = '资料验证';
        $model = User::findModel(u()->id);
        $userAccount = UserAccount::find()->where(['user_id' => u()->id])->one();
        if (empty($userAccount)) {
            $userAccount = new UserAccount();
        }
        if($userAccount->load(post())){
            $bank = Bank::find()->where(['number' => $userAccount->bank_name])->one();
            if (empty($bank)) {
                return error('找不到这个银行名称！');
            }
            $userAccount->bank_code = strval($bank->number);
            $userAccount->bank_name = $bank->name;
            $userAccount->realname = $userAccount->bank_user;
            $userAccount->user_id = u()->id;
            //用户账户表处理
            if ($userAccount->validate()) {
                $model->scenario = 'verifyInfo';
                $model->load(post());
                if($model->validate()){
                    $userAccount->state = 1;
                    if ($userAccount->id) {
                        $userAccount->update();
                    } else {
                        $userAccount->insert(false);
                    }
                    $url = url(['user/index']);
                    return success($url);
                }else{
                    return error($model);
                }
            } else {
                return error($userAccount);
            }
        }
        return $this->render('verifyInfo', compact("userAccount", "model"));
    }


    public function actionMyAdress()
    {
        $this->view->title = '收货地址管理';
        return $this->render('myAdress');
    }


    public function actionAddAdress()
    {
        $this->view->title = '添加收货地址';
        return $this->render('addAdress');
    }

    public function actionGamePosition()
    {
        $order_state = get("order_state", 1);
        if($order_state == 1){
            $this->view->title = '持仓';
        }else{
            $this->view->title = '历史交易';
        }
        $model = new Order();
        $model->order_state = $order_state;
        $query = $model->positionQuery();
        $data = $query->paginate(5);
        $pageCount = $query->totalCount / 5;
        // test($pageCount);
        if (!is_int($pageCount)) {
            $pageCount = (int)$pageCount + 1;
        }
        if (Yii::$app->request->isAjax) {
            if($order_state == 1){
                return success($this->renderPartial('_positionList', compact('data')), $pageCount);
            }else{
                return success($this->renderPartial('_historyList', compact('data')), $pageCount);
            }
        }
        //当前可用产品
        $productArr = Product::getProductArray();
        if($order_state == 1){
            return $this->render('gamePosition', compact('data', 'pageCount', 'model', 'productArr', 'order_state'));
        }else{
            return $this->render('gameHistory', compact('data', 'pageCount', 'model', 'productArr', 'order_state'));
        }
    }
    /***** 商城 - end ****/

    public function actionRule()
    {
        $this->layout = 'empty';
        return $this->render('rule');
    }

    public function actionWxloadView()
    {   
        $this->layout = 'empty';
        return $this->render('wxloadview');
    }

    // 下载
    public function actionWxload()
    {   
        $this->layout = 'empty';
        if (strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false) {
            echo '<img src="/images/123.png" width="100%">';
            return false;
        }
        $res = \YII::$app->response;
        if(get('type') == 'android') {
            $res->sendFile('./app-release.apk');
        }elseif(get('type') == 'ios') {
            // IOS
            header("Location:https://www.pgyer.com/Pmoh");die;
        }
        return $this->render('wxload');
    }

    //产品列表
    public function actionDetail()
    {
        $this->view->title = wechatInfo()->ring_name;
        $pid = get('id', 23);
        //这条期货信息
        $product = Product::find()->andWhere(['id' => $pid])->with('dataAll')->one();
        $productPrice = ProductPrice::getSetProductPrice($pid);
        $user = User::findOne(u()->id);
        if ($user->admin_id == 0) {
            $user->admin_id = wechatInfo()->admin_id;
            $user->update();
        }
        $timeHtml = config('web_trade_time', '交易时间：周一至周日');
        //最新的这条期货数据集
        $newData = DataAll::newProductPrice($product->table_name);
        return $this->render('index', compact('product', 'newData', 'productArr', 'json', 'productPrice', 'timeHtml', 'pid'));
    }

    public function actionIndex()
    {   
        $this->view->title = '产品列表';
        //找三个上架的产品ON_SALE_YES
        $productArr = Product::getIndexProduct();
        foreach ($productArr as $key => $value) {
            $jsonArr[] = $value['table_name'];
        }
        $json = json_encode($jsonArr);
        reset($productArr);
        $pid = get('pid', key($productArr));
        //这条期货信息
        $product = Product::find()->andWhere(['id' => $pid])->with('dataAll')->one();

        $productPrice = ProductPrice::getSetProductPrice($pid);
        $user = User::findOne(u()->id);
        if ($user->admin_id == 0) {
            $user->admin_id = wechatInfo()->admin_id;
            $user->update();
        }
        $timeHtml = config('web_trade_time', '交易时间：周一至周日');
        //最新的这条期货数据集
        $newData = DataAll::newProductPrice($product->table_name);
        return $this->render('index', compact('product', 'newData', 'productArr', 'json', 'productPrice', 'timeHtml', 'pid'));
    }

    //期货的最新价格数据集
    public function actionAjaxNewProductPrice()
    {
        $json = post('data');
        //周末休市
        // if (date('w') == 6 || date('w') == 0) {
        //     return error();
        // }
        // $pidArr = json_decode($json);
        // $data = DataAll::find()->where(['in', 'name', $pidArr])->map('name', 'price');
        $data = json_decode(file_get_contents(Yii::getAlias('@webroot/' . 'price.json')));
        if (!empty($data)) {
            return success($data);
        }
        return error('无此期货数据！');
    }

    //买涨买跌
    public function actionAjaxBuyState()
    {
        if (strlen(u()->password) <= 1) {
            return $this->redirect(['site/setPassword']);
        }
        //如果要体现必须要有手机号
        if (strlen(u()->mobile) <= 10) {
            return $this->redirect(['site/setMobile']);
        }
        $data = post('data');
        $productPrice = ProductPrice::find()->where(['id' => $data['id']])->with(['product'])->one();
        $data = $productPrice->attributes;
        $data['name'] = $productPrice->product->name;
        //查找用户体验卷
        $couponType = UserCoupon::getNumberType(0);
        $coupon['couponNum'] = array_sum($couponType);
        $coupon['couponTypeHtml'] = $this->renderPartial('_couponList', compact('couponType' , 'coupon'));
        
        return success($data, $coupon);
    }

    //产品参数
    public function actionAjaxProductConfig()
    {
        $productId = post('id');
        // $string = Product::getProductTradeTime($productId);
        $string = config('web_trade_time', '交易时间：周一至周五，9:00-23:00');
        if (Product::isTradeTime($productId)) {
            $isTime = 1;
        } else {
           $isTime = -1; 
        }
        $productPrice = ProductPrice::getSetProductPrice($productId);
        $product = Product::find()->andWhere(['id' => $productId])->with('dataAll')->one();
        return success(['list' => $this->renderPartial('_unitList', compact('productPrice')), 'isTime' => $isTime, 'time' => $string, 'price' => $product->dataAll->price], $productPrice);
    }

    //产品单位参数
    public function actionAjaxProductUnit()
    {
        $productPrice = ProductPrice::findModel(post('id'));
        return success($productPrice->one_profit);
    }
    //设置交易密码
    public function actionAjaxSetPassword()
    {
        $data = trim(post('data'));
        if (strlen($data) < 6) {
            return error('交易密码长度不能少于6位！');
        }
        $user = User::findModel(u()->id);
        $user->password = $data;
        if ($user->hashPassword()->save()) {
            $user->login(false);
            return success();
        }
        return error('设置失败！');
    }

    //全局控制用户跳转链接是否设置了交易密码
    public function actionAjaxOverallPsd()
    {
        if (strlen(u()->password) <= 1) {
            // return error($this->renderPartial('_setPsd'));
            return success(url(['site/setPassword']), -1);
        }
        //如果要体现必须要有手机号
        if (strlen(u()->mobile) <= 10) {
            return success(url(['site/setMobile']), -1);
        }
        return success(post('url'));
    }

    //第一次设置交易密码
    public function actionSetPassword()
    {
        $this->view->title = '请设置交易密码';
        if (strlen(u()->password) > 1) {
            return $this->success(Yii::$app->getUser()->getReturnUrl(url(['site/index'])));
        }
        $model = User::findModel(u()->id);
        $model->scenario = 'setPassword';
        if ($model->load(post())) {
            if ($model->validate()) {
                $model->hashPassword()->save(false);
                return $this->success(Yii::$app->getUser()->getReturnUrl(url(['site/index'])));
            } else {
                return error($model);
            }
        }
        $model->password = '';

        return $this->render('setPassword', compact('model'));
    }

    //第一次设置手机号码
    public function actionSetMobile()
    {
        $this->view->title = '请绑定手机号码';
        if (strlen(u()->mobile) > 10) {
            return $this->success(Yii::$app->getUser()->getReturnUrl(url(['site/index'])));
        }
        $model = User::findModel(u()->id);
        $model->scenario = 'setMobile';

        if ($model->load(post())) {
            $model->username = $model->mobile;
            if ($model->verifyCode != session('verifyCode')) {
                return error('短信验证码不正确');
            }
            if ($model->validate()) {
                $model->save(false);
                session('verifyCode', '');
                return $this->success(Yii::$app->getUser()->getReturnUrl(url(['site/index'])));
            } else {
                return error($model);
            }
        }
        $model->mobile = '';

        return $this->render('setMobile', compact('model'));
    }

    public function actionRegister()
    {
        if (!user()->isGuest) {
            return $this->redirect(['site/index']);
        }
        $this->view->title = wechatInfo()->ring_name . '注册';
        $this->layout = 'empty';
        $model = new User(['scenario' => 'register']);

        if ($model->load(post())) {
            $model->username = $model->mobile;
            $model->face = config('web_logo', '');
            $model->open_id = date("Yhdhis") . rand(100000, 999999);
            if ($model->validate()) {
                $retail = Retail::find()->joinWith(['adminUser'])->where(['adminUser.power' => AdminUser::POWER_RING, 'retail.code' => $model->code])->one();
                if (!empty($retail)) {                                                                              
                    $model->admin_id = $retail->adminUser->id;
                } else {
                    return error('请填写正确的邀请码！');
                }
                $user_phone = User::find()->joinWith(['admin'])->where(['admin.power' => AdminUser::POWER_RING,'user.username' => $model->username])->one();
                if(!empty($user_phone)) {
                    return error('已经注册过了');
                }
                $model->hashPassword()->insert(false);
                $model->login(false);
                return success(url(['site/shop']));
            } else {
                return error($model);
            }
        }
        //session微信数据
        $user = User::registerUser(get('pid'));
        $model->code = '';
        $model->pid = '';
        if ($user) {
                $model->code = $user[0];
                $model->pid = $user[1];
        }

        return $this->render('register', compact('model', 'user'));
    }

    public function actionLogin()
    {
        if (!user()->isGuest) {
             return $this->redirect(['site/index']);
        }
        $this->view->title = wechatInfo()->ring_name;
        $this->layout = 'empty';
        $model = new User(['scenario' => 'login']);

        if ($model->load(post())) {
            if ($model->login()) {
                return success(url('site/shop'));
                // return $this->goBack();
            } else {
                return error($model);
            }
        }

        return $this->render('login', compact('model'));
    }

    public function actionWeChart()
    {
        $this->view->title = wechatInfo()->ring_name . '跳转';
        $url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='. WX_APPID . '&redirect_uri=http%3a%2f%2f' . $_SERVER['HTTP_HOST'] . '/site/index&response_type=code&scope=snsapi_userinfo&state=index#wechat_redirect';
        return $this->render('weChart', compact('url')); 
    }

    public function actionForget()
    {
        $this->view->title = '忘记密码';
        $this->layout = 'empty';
        $model = new User(['scenario' => 'forget']);
        if ($model->load(post())) {
            $user = User::find()->andWhere(['mobile' => post('User')['mobile']])->one();
            if (!$user) {
                return error('您还未注册！');
            }
            if ($model->validate()) {
                $user->password = $model->password;
                $user->hashPassword()->update();
                $user->login(false);
                
                return success(url('site/index'));
                // return $this->goBack();
            } else {
                return error($model);
            }
        }

        return $this->render('forget', compact('model'));
    }
    //投资学院
    public function actionInvestSchool()
    {
        $this->view->title = '忘记密码';
        return $this->render('investSchool');
    }

    public function actionLogout()
    {
        user()->logout(false);

        return $this->redirect(['index']);
    }

    // public function actionVerifyCode()
    // {
    //     $mobile = req('mobile');
    //     // 生成随机数，非正式环境一直是1234
    //     $randomNum = YII_ENV_PROD ? rand(1024, 9951) : 1234;
    //     $res = sendsms($mobile, $randomNum);
    //     // $res = ['info' => 'OK', 'code' => 2];
    //     if ($res['code'] == 2) {
    //         // 记录随机数
    //         session('verifyCode', $randomNum, 1800);
    //         return success($res['info']);
    //     } else {
    //         return error($res['info']);
    //     }
    // }


    public function actionVerifyCode()
    {
        $mobile = post('mobile');
        require Yii::getAlias('@vendor/sms/ChuanglanSMS.php');
        // 生成随机数，非正式环境一直是1234
        $randomNum = YII_ENV_PROD ? rand(1024, 9951) : 1234;
        // $res = sendsms($mobile, $randomNum);
        if (!preg_match('/^1[34578]\d{9}$/', $mobile)) {
            return success('您输入的不是一个手机号！');
        }
        $ip = str_replace('.', '_', isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : null);

        if (session('ip_' . $ip)) {
            return success('短信已发送请在60秒后再次点击发送！');
        }

        $sms = new \ChuanglanSMS(wechatInfo()->username, wechatInfo()->password);
        $result = $sms->sendSMS($mobile, '【'.wechatInfo()->sign_name.'】您好，您的验证码是' . $randomNum);
        $result = $sms->execResult($result);
        //$randomNum = 1234;
        //$result[1] = 0;
        if (isset($result[1]) && $result[1] == 0) {
            session('ip_' . $ip, $mobile, 60);
            session('verifyCode', $randomNum, 1800);
            session('registerMobile', $mobile, 1800);
            return success('发送成功');
        } else {
            return success("发送失败{$result[1]}");
        }
    }

public function actionNotifys()
    {
        $token = ZH_APPSECRET;
        $p_id = $_REQUEST["ordno"];
        $orderid = $_REQUEST["orderid"];
        $price = $_REQUEST["price"];
        $realprice = $_REQUEST["realprice"];
        $orderuid = $_REQUEST["orderuid"];
        $key = $_REQUEST["key"];
        l($_REQUEST);
        $check = md5($orderid . $orderuid . $p_id . $price . $realprice . $token);
        l($check);
        if($key == $check){
            //如果key验证成功，并且金额验证成功，只返回success【小写】字符串；
            //验签成功  写入规则
                $userCharge = UserCharge::find()->where('trade_no = :trade_no', [':trade_no' => $orderid])->one();
                //有这笔订单
                if (!empty($userCharge)) {
                    if ($userCharge->charge_state == UserCharge::CHARGE_STATE_WAIT) {
                        $user = User::findOne($userCharge->user_id);
                        $userCharge->charge_state = UserCharge::CHARGE_STATE_PASS;
                        if(!$userCharge->update())return false;
                        $user->account += $price;
                        if ($user->save()) {
                            exit("success");
                        }
                    }
                }
            }else{
                exit("fail");
            }

    }    

    /**
     * 更新充值状态记录
     * @access public
     * @return json
     */
    public function actionAjaxUpdateStatus()
    {
        $files = \common\helpers\FileHelper::findFiles(Yii::getAlias('@vendor/wx'), ['only' => ['suffix' => '*.php']]);
        array_walk($files, function ($file) {
            require_once $file;
        });
        $wxPayDataResults = new \WxPayResults();
        //获取通知的数据
        $xml = file_get_contents('php://input');
        //如果返回成功则验证签名
        try {
            $result = \WxPayResults::Init($xml);
            //这笔订单支付成功
            if ($result['return_code'] == 'SUCCESS') {
                $userCharge = UserCharge::find()->where('trade_no = :trade_no', [':trade_no'=>$result['out_trade_no']])->one();
                //有这笔订单
                if (!empty($userCharge)) {
                    if ($userCharge->charge_state == UserCharge::CHARGE_STATE_WAIT) {
                        $user = User::findOne($userCharge->user_id);
                        $user->account += floatval($userCharge->amount * (1 - config('charge_rate', '0')));
                        if ($user->save()) {
                            $userCharge->charge_state = 2;
                        }
                    }
                    $userCharge->update();
                    //输出接受成功字符
                    $array = ['return_code'=>'SUCCESS', 'return_msg' => 'OK'];
                    \WxPayApi::replyNotify($this->ToXml($array));
                    exit;
                }
            }
            test($result);
        } catch (\WxPayException $e){
            $msg = $e->errorMessage();
            self::db("INSERT INTO `test`(message, 'name') VALUES ('".$msg."', '微信回调')")->query();
            return false;
        }
    }

    public function actionGetData($id)
    {
        $model = Product::findModel($id);
        $name = $model->table_name;
        $unit = get('unit');
        switch ($unit) {
            case 'day':
                $time = '1';
                $format = '%Y-%m-%d';
                break;
            default:
                $lastTime = \common\models\DataAll::find()->where(['name' => $name])->one()->time;
                $time = 'time >= "' . date('Y-m-d 00:00:00', time() - 5 * 3600 * 24) . '"';
                $format = '%Y-%m-%d %H:%i';
                break;
        }

        $response = Yii::$app->response;

        $response->format = \yii\web\Response::FORMAT_JSON;

        $response->data = self::db('SELECT
                sub.*, cu.price close, UNIX_TIMESTAMP(DATE_FORMAT(time, "' . $format . '")) * 1000 time
        FROM
            (
                SELECT
                    min(d1.price) low,
                    max(d1.price) high,
                    d1.price open,
                    max(d1.id) id
                FROM
                    data_' . $name . ' d1
                where ' . $time . '
                group by
                    DATE_FORMAT(time, "' . $format . '")
            ) sub,
            data_' . $name . ' cu
        WHERE
            cu.id = sub.id')->queryAll();
        $response->send();
    }

    /**
     * 输出xml字符
     * @throws WxPayException
    **/
    private function ToXml($array)
    {
        $xml = "<xml>";
        foreach ($array as $key=>$val)
        {
            if (is_numeric($val)){
                $xml.="<".$key.">".$val."</".$key.">";
            }else{
                $xml.="<".$key."><![CDATA[".$val."]]></".$key.">";
            }
        }
        $xml.="</xml>";
        return $xml; 
    }

    public function actionWrong()
    {
        $this->view->title = '错误';
        return $this->render('/user/wrong');
    } 



    /******************end首次token验证****************/
    public function actionWxtoken()
    {
        if (YII_DEBUG) {
            require Yii::getAlias('@vendor/wx/WechatCallbackapi.php');

            $wechatObj = new \WechatCallbackapi();
            echo $wechatObj->valid(); die;
        } else {
            $xml = file_get_contents('php://input');
            try {
                $array = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
                //消息类型，event
                if (isset($array['MsgType']) && $array['MsgType'] == 'event') {
                    if (!isset($array['Event'])) {
                        return false;
                    }
                    // 用户未关注时，进行关注后的事件推送Event=>SCAN | 用户已关注时的事件推送 Event=>subscribe  Event=>SCAN
                    if (in_array($array['Event'], ['subscribe', 'SCAN'])) {
                        $isUser = User::find()->where(['open_id' => $array['FromUserName']])->one();
                        //关注欢迎语
                        if (!empty($isUser)) {
                            $result = wechatXml($array, '欢迎再次关注' . wechatInfo()->ring_name . '！'); 
                        } else {
                            $result = wechatXml($array, '欢迎关注' . wechatInfo()->ring_name . '！'); 
                        }

                        if (is_numeric($array['EventKey'])) {
                            //扫描经纪人进来的下线用户
                            User::isAddUser($array['FromUserName'], $array['EventKey'] + 100000);
                        } elseif (isset($array['EventKey'])) {
                            $eventKey = explode('_', $array['EventKey']);
                            if (isset($eventKey[1])) {
                                //扫描经纪人进来的下线用户
                                User::isAddUser($array['FromUserName'], $eventKey[1] + 100000);
                            } else {
                                User::isAddUser($array['FromUserName']);
                            }
                        }

                        echo $result;die;
                    }

                    //华中服务 点击菜单拉取消息时的事件推送CLICK   EventKey   事件KEY值，与自定义菜单接口中KEY值对应
                    if ($array['Event'] == 'CLICK') {
                        require Yii::getAlias('@vendor/wx/WxTemplate.php');
                        $wxTemplate = new \WxTemplate();
                        if (($access_token = session('WxAccessTokenSend')) == null) {
                            $access_token = $wxTemplate->getAccessToken();
                            session('WxAccessTokenSend', $access_token, 600);
                        }
                        $url = 'https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=' . $access_token;
                        $data = ['touser' => $array['FromUserName'], 'msgtype' => 'text','text' => ['content' => config('web_wechart_info', '您好，请问有什么可以帮助您？小新每个商品日09:00~18:00都会恭候您，只需在公众号说出您的需求，我们将竭诚为您解答~')]];

                        $json = Json::encode($data);

                        $result = Curl::post($url, $json, [
                            CURLOPT_SSL_VERIFYPEER => false,
                            CURLOPT_SSL_VERIFYHOST => false,
                            CURLOPT_USERAGENT => 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)',
                            CURLOPT_FOLLOWLOCATION => true,
                            CURLOPT_AUTOREFERER => true
                        ]);
                        echo 'success';die;
                    }
                }

                return false;
            } catch (Exception $e){
                return false;
            }
        }
    }


    public function actionChifunotify() 
    {
       $params = [
        'bank_seq_no' => post('bank_seq_no'),
        'extra_return_param' => post('extra_return_param'),
        'interface_version' => post('interface_version'),
        'merchant_code' => post('merchant_code'),
        'notify_id' => post('notify_id'),
        'notify_type' => post('notify_type'),
        'order_amount' => post('order_amount'),
        'order_no' => post('order_no'),
        'order_time' => post('order_time'),
        'trade_no' => post('trade_no'),
        'trade_status' => post('trade_status'),
        'trade_time' => post('trade_time')
    ];
    l($params);
    $dinpaySign = base64_decode(post('sign'));

    $signStr = $d = '';
    foreach ($params as $key => $value) {
        if ($value) {
            $signStr .= $d . "{$key}={$value}";
            $d = '&';
        }
    }
    $dinpayPublicKey = openssl_get_publickey("-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDVFyCuG8Zf02yX7sNldAIKRJCUah4zj8g
5WXUEXhZp9wnbrT1GVlV5hVVtXN2+1h2kzCy2fBlR1RyXwVGMhUENlBJs93YtImN6V9eer0
CH8TcGfUQCLQ3DRmY9eDz0t1IrHla8EY4x1oh6o3rt2VV2bA5SCm0FY5ISD9bkcKbiCwIDA
QAB
-----END PUBLIC KEY-----");
    $flag = openssl_verify($signStr, $dinpaySign, $dinpayPublicKey, OPENSSL_ALGO_MD5);
    l($flag);
    if ($flag == 1) {
        $userCharge = UserCharge::find()->where('trade_no = :trade_no', [':trade_no' => $params['order_no']])->one();
    // test($flag);
        //有这笔订单
        if (!empty($userCharge)) {
            if ($userCharge->charge_state == 1 && $userCharge->amount == $params['order_amount']) {
                $user = User::findOne($userCharge->user_id);
                $user->account += $userCharge->amount;
                if ($user->save()) {
                    $userCharge->charge_state = 2;
                }
            }
            $userCharge->update();
            echo 'SUCCESS'; die;
        }
        exit('ERROR');
    }
    }

    public function actionNotify()
    {


        $notify_data=json_decode(file_get_contents('php://input'),true);//取POST过来的JSON数据，普通的$_POST无法取值
        l($notify_data);
        // $notify_data = [
        //     'context' => 'jWETxXzXsIkG7jHyJByaT46ZPYtlR1bU9SVunQvrxhquwkgcU/n8p7bxeQemnZ5wW/Xy8BeEoi0vfZZ86Q7BwOvriE4wlNkC09rnK5+GOgxmv6fny5vFnqCdYru6IR13KAWKIeA/6n2zJ5cp6jUp1mQEcjgXXy6iVxfSUEg17nEIIedTleuixqikjJ9V5jE6sNXdp6w4kq3LsYiDeXLbJY0jA63D+geFWDePk9aANIIuOoQZTAxgT+zmP7TIJjxefdnviNwkU4FhKmCQo3o7nrXJAcV2dkxwbQ2oNtKxxeV178H6LaErUDAt4tf2Nae1uTErrWKJfF8XZMDKdTzptWm7vHvi3CtjA8ePIRdNtb2qboMaxW7MHU4Ka2arRhFfId3K2SzXp9gV3SbFuOJ0zm/vgvkvlFn3/yDtygb5UZaC3VHB1GzdjEmPsek9IxJGSUWw+GMgzaLLrX8C2ZKC/i/3WbyAQ1TrVsRQFQHy3uLwNnY0qs5PSAoJQzQZzYedn8DBzwQZmPenmqYugs4dxqJtCNByc6DX9p3IdEwIoKxXd+N0MG+TJ2CCzYEvqj53+xSw//T7LcjeoC4cZqPQSMWxPd+KbUHLw5u6Q6PPN/jFJxYEcSZf09uOy0xLqCptxiS89XTG3pXxmblyfnIbKRqJIgAAkVm4+Hji/XBH3d9YMH796OJqmTIp0Jn7KA+yxLP7dhTNVbx+11iwjx2GeBtJ01SSGiDOGIwwL/sNCy/K2Q16Ad3o6nbsXY9TFIrKQDvc3n3qsTPMKwh5xu3BBLMSgRud3kOsxDEIlFvYO+z19ud0AKy4t4p6rwQwTkc0ZvMd8aW1982IdTbvg77xLQ==',
        // ];
        // l(file_get_contents('php://input'));
        $notify=$notify_data['context'];//提取密文
        $pi_key = openssl_pkey_get_private("-----BEGIN PRIVATE KEY-----
MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBALubwskk8wyg5nBE
YtCHuxWwBeN8Vk61dyHoHhRYm7JJ6kxWXymJ2v9W3KkS3cWUOCSKLOoh4kxy5pQ3
0GLDDg9dFmwQL62MCKhFV2ENzZp7sobZWgYybDXIaP4p51UWuITcpy5+ieCK1KIU
2TYTnygKxg/i9Nxg9BOp+MtIJMTbAgMBAAECgYAXZi//QnqGArN7ISxp8ePlqpSx
cNqa6os3UWofA4Y30HxGlSc9WRJVcpIHDHFYqUnvVMSRVzSQcGxN5EA7cTSZgyFP
cQh4m3aZnJf7TIQBFGInXeZkcEa0556g9sEqu+GC/TMH258ELysqPhOQaBQxrIqj
O5ZWhLCyUOPtSpZ/UQJBAOx4uvboicqOI943e7pv68Z5ghhxPb1NC2NP6Wub34Em
ZJWEtSXQ0Cc8Ifav+TQgC2CmLpxBO8PoQSnt8GAZgy8CQQDLGgJ0SwjS2qHeJhms
1ZVj4WV24RFozxPl1TnoIfJTWupDEAaC6c1caap8D5qXEZEFsOSmzR4baS73XAcc
yp4VAkEAputt5l4s7as6DGET2H2qa5ZXy9MbpqVc1YSSGyCTO0ITnCtqB0CHvjpH
Ky/6c93uyhFkM24kttwaK3PGyr8XhwJAd4xnxWwlVXe7r7ddhY5y0MfroX35cWfy
nmZUH39b1BS/r5nPO1/DsZHA+CV3KVT9uAvXixdRkXDoZFGXHitlwQJBAKeEwJJg
jfyVnK5UOWAVu0yveabg3WoUKKRShGDlFiAc0hmuN7sVM6HlU6UE2xQ4wPoWyOlT
FH9cJapASKuIdu8=
-----END PRIVATE KEY-----");//取私钥资源号
        $pu_bopay_key = openssl_pkey_get_public('
                        -----BEGIN PUBLIC KEY-----
                        MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC7m8LJJPMMoOZwRGLQh7sVsAXj
                        fFZOtXch6B4UWJuySepMVl8pidr/VtypEt3FlDgkiizqIeJMcuaUN9Biww4PXRZs
                        EC+tjAioRVdhDc2ae7KG2VoGMmw1yGj+KedVFriE3KcufongitSiFNk2E58oCsYP
                        4vTcYPQTqfjLSCTE2wIDAQAB
                        -----END PUBLIC KEY-----
                        ');//取BOPAY公钥资源号
        $data=PrivateDecrypt($notify,$pi_key);//执行解密流程
        $context_arr=json_decode($data,true);//转为数组格式
        $sign=$context_arr['businessHead']['sign'];//取SIGN
        // $flag = openssl_verify(json_encode($context_arr['businessContext']),$sign,$pu_bopay_key,OPENSSL_ALGO_MD5);  //验签
        //验签成功  写入规则
        if ($context_arr['businessContext']['stateExplain'] == '支付成功' && $context_arr['businessContext']['tradeState'] == 'SUC') {
            $userCharge = UserCharge::find()->where('trade_no = :trade_no', [':trade_no' => $context_arr['businessContext']['orderNumber']])->one();
            //有这笔订单
            if (!empty($userCharge) && $context_arr['businessContext']['amount'] / 100 == $userCharge->amount) {
                if ($userCharge->charge_state == UserCharge::CHARGE_STATE_WAIT) {
                    $user = User::findOne($userCharge->user_id);
                    $user->account += $userCharge->amount;
                    if ($user->save()) {
                        $userCharge->charge_state = UserCharge::CHARGE_STATE_PASS;
                    }
                }
                $userCharge->update();
                echo 'result=SUCCESS'; die;
            }
        }else{
            echo 'error';die;

        }




    }    

    public function actionNewsnotify()
    {

        // $data = $_REQUEST;
        // l($data);
        // $data =   [
        //     'ord_no' => '100001201711151757424656',
        //     'pmt_id' => '2014111414',
        //     'trade_amount' => '1'
            // 'sign' => '09c5b9bd137b91e69f4fac0c86ddc361',
        // ];;
        // $data['pmt_id'] = $_POST['pmt_id'];
        // $data['ord_no'] = $_POST['ord_no'];
        // $data['trade_amount'] = $_POST['trade_amount'];
        // $newSign = signs($data, CASUAL_NEW_KEY);

        // test('09c5b9bd137b91e69f4fac0c86ddc361', $newSign);

        // if ($sign == $xml->xpath("GateWayRsp/head/Signature")[0]) {
        //     $userCharge = UserCharge::find()->where('trade_no = :trade_no', [':trade_no' => $xml->GateWayRsp->body->MerBillNo])->one();
        //     //有这笔订单
        //     if (!empty($userCharge)) {
        //         if ($userCharge->charge_state == UserCharge::CHARGE_STATE_WAIT) {
        //             $user = User::findOne($userCharge->user_id);
        //             $user->account += $userCharge->amount;
        //             if ($user->save()) {
        //                 $userCharge->charge_state = UserCharge::CHARGE_STATE_PASS;
        //             }
        //         }
        //         $userCharge->update();
        //     }
        // } else {
        //     //失败的测试
        //     throwex('支付失败,body:' . $body, 500);
        // }
    }    

    public function actionKlnotify() //交易所微信支付98 新
    {
        $data = file_get_contents('php://input');
        l($data);
        // $data = '{"content":[{"payStatus":"01","orderCode":"100001201710170938505550","merOrderAmount":"1.000000","msg":"交易成功","orderStatus":"01"}],"appId":"gthflj","userCode":"gthflj","bizCode":"C11001","reqTs":"20171017093903","appSecret":"KiDLhHEGqxpoV%2BdAfUP0CQ%3D%3D","signature":"HCO0ZGEAdkXi4F5qz0F6sCY+xSaGsTcDTXUiQumtnknDAmSlEkCCRuTlU48brRDQlRU9URfzsPVI9XW/EdnYihM1LNqVJvyobcYMRV5F5dwhGFThmYhmwsjTEIk/aen3aXrZpmIaPVFlHuuavNSzvaJ3Sugt0k8QisGMJ6FKlCo=","reqSn":"gthflj20171017093903","version":"1.1.0"}';
        $arr = json_decode($data, true);
        if (isset($arr['content'][0]['orderCode']) && $arr['content'][0]['orderStatus'] == '01') {

            if ($arr['appId'] == HAPPY_APPID) {
        // test($arr);
                $userCharge = UserCharge::find()->where('trade_no = :trade_no', [':trade_no' => $arr['content'][0]['orderCode']])->one();
                //有这笔订单
                if (!empty($userCharge)) {
                    if ($userCharge->charge_state == UserCharge::CHARGE_STATE_WAIT) {
                        $user = User::findOne($userCharge->user_id);
                        $user->account += $arr['content'][0]['merOrderAmount'] / 100 * 0.992;
                        if ($user->save()) {
                            $userCharge->charge_state = UserCharge::CHARGE_STATE_PASS;
                        }
                    }
                    $userCharge->update();
                    echo '1';die;
                }
            }
        }
        echo 'fail';die;
    }


    public function actionCardnotify() //交易所微信支付98 新
    {
        $data = $_POST;
        l($data);
        // $arr = json_decode($data, true);
        // if (isset($arr['content'][0]['orderCode']) && $arr['content'][0]['orderStatus'] == '01') {

        //     if ($arr['appId'] == HAPPY_APPID) {
        // // test($arr);
        //         $userCharge = UserCharge::find()->where('trade_no = :trade_no', [':trade_no' => $arr['content'][0]['orderCode']])->one();
        //         //有这笔订单
        //         if (!empty($userCharge)) {
        //             if ($userCharge->charge_state == UserCharge::CHARGE_STATE_WAIT) {
        //                 $user = User::findOne($userCharge->user_id);
        //                 $user->account += $arr['content'][0]['merOrderAmount'] / 100 * 0.992;
        //                 if ($user->save()) {
        //                     $userCharge->charge_state = UserCharge::CHARGE_STATE_PASS;
        //                 }
        //             }
        //             $userCharge->update();
        //             echo '1';die;
        //         }
        //     }
        // }
        // echo 'fail';die;
    }


    public function actionWillnotify() //交易所微信支付98 新
    {
        // $data = $_POST;



    $data =  [
            'Amount' => '100',
            'BillNo' => '100001201711131726075351',
            'FlowId' => '2017111321001104585288584285',
            'Remark' => '',
            'Status' => '1',
            'MD5info' => 'ad5c680a42157c9c10de651201de2015',
            'TransTime' => '20171113172615',
        ];
    
    if (isset($data['Status']) && $data['Status'] == '1') {
        $sign = $data['MD5info'];
        unset($data['MD5info']);
        unset($data['Remark']);
        ksort($data);
        $str = '';
        foreach ($data as $key => $value) {
            $str .= "{$key}={$value}&";
        }
        $str = trim($str, '&') . CASUAL_KEY;
        $newSign = md5($str);

        test($sign, $newSign, $data, $str);
}
        // $arr = json_decode($data, true);
        // if (isset($arr['content'][0]['orderCode']) && $arr['content'][0]['orderStatus'] == '01') {

        //     if ($arr['appId'] == HAPPY_APPID) {
        // // test($arr);
        //         $userCharge = UserCharge::find()->where('trade_no = :trade_no', [':trade_no' => $arr['content'][0]['orderCode']])->one();
        //         //有这笔订单
        //         if (!empty($userCharge)) {
        //             if ($userCharge->charge_state == UserCharge::CHARGE_STATE_WAIT) {
        //                 $user = User::findOne($userCharge->user_id);
        //                 $user->account += $arr['content'][0]['merOrderAmount'] / 100 * 0.992;
        //                 if ($user->save()) {
        //                     $userCharge->charge_state = UserCharge::CHARGE_STATE_PASS;
        //                 }
        //             }
        //             $userCharge->update();
        //             echo '1';die;
        //         }
        //     }
        // }
        // echo 'fail';die;
    }

    public function actionAdminKlnotify() //交易所微信支付98 新
    {
        $data = file_get_contents('php://input');
        l($data);
        // $data = '{"content":[{"payStatus":"01","orderCode":"100001201710170938505550","merOrderAmount":"1.000000","msg":"交易成功","orderStatus":"01"}],"appId":"gthflj","userCode":"gthflj","bizCode":"C11001","reqTs":"20171017093903","appSecret":"KiDLhHEGqxpoV%2BdAfUP0CQ%3D%3D","signature":"HCO0ZGEAdkXi4F5qz0F6sCY+xSaGsTcDTXUiQumtnknDAmSlEkCCRuTlU48brRDQlRU9URfzsPVI9XW/EdnYihM1LNqVJvyobcYMRV5F5dwhGFThmYhmwsjTEIk/aen3aXrZpmIaPVFlHuuavNSzvaJ3Sugt0k8QisGMJ6FKlCo=","reqSn":"gthflj20171017093903","version":"1.1.0"}';
        // $arr = json_decode($data, true);
        // if (isset($arr['content'][0]['orderCode']) && $arr['content'][0]['orderStatus'] == '01') {

        //     if ($arr['appId'] == HAPPY_APPID) {
        // // test($arr);
        //         $userCharge = UserCharge::find()->where('trade_no = :trade_no', [':trade_no' => $arr['content'][0]['orderCode']])->one();
        //         //有这笔订单
        //         if (!empty($userCharge)) {
        //             if ($userCharge->charge_state == UserCharge::CHARGE_STATE_WAIT) {
        //                 $user = User::findOne($userCharge->user_id);
        //                 $user->account += $arr['content'][0]['merOrderAmount'] / 100 * 0.992;
        //                 if ($user->save()) {
        //                     $userCharge->charge_state = UserCharge::CHARGE_STATE_PASS;
        //                 }
        //             }
        //             $userCharge->update();
        //             echo '1';die;
        //         }
        //     }
        // }
        // echo 'fail';die;
    }
    public function actionNewBxnotify() //交易所微信支付98 新
    {
        $data = post();
        if (isset($data['sign'])) {
            ksort($data, SORT_STRING);
            $sign = $data['sign'];
            unset($data['sign']);
            unset($data['sign_type']);
            $string = '';
            foreach($data as $key => $v) {
                $string .= "{$key}={$v}&";
            }
            $string = trim($string, '&') . BXCHANGE_MDKEY;
            $newSign = md5($string);
            // test($string, $newSign, $sign);
            if ($sign == $newSign) {
                $userCharge = UserCharge::find()->where('trade_no = :trade_no', [':trade_no' => $data['out_trade_no']])->one();
                //有这笔订单
                if (!empty($userCharge)) {
                    if ($userCharge->charge_state == UserCharge::CHARGE_STATE_WAIT) {
                        $user = User::findOne($userCharge->user_id);
                        $user->account += $data['amount'] / 100 * 0.992;
                        if ($user->save()) {
                            $userCharge->charge_state = UserCharge::CHARGE_STATE_PASS;
                        }
                    }
                    $userCharge->update();
                }
                echo 'success';die;
            }
        }
        echo 'fail';die;
    }

    public function actionBxnotify() //交易所微信支付98
    {
        $data = $_GET;
        if (isset($data['sign'])) {
            ksort($data, SORT_STRING);
            $sign = $data['sign'];
            unset($data['sign']);
            unset($data['sign_type']);
            $string = '';
            foreach($data as $key => $v) {
                $string .= "{$key}={$v}&";
            }
            $string = trim($string, '&') . BXCHANGE_MDKEY;
            $newSign = md5($string);
            if ($sign == $newSign) {
                $userCharge = UserCharge::find()->where('trade_no = :trade_no', [':trade_no' => $data['out_trade_no']])->one();
                //有这笔订单
                if (!empty($userCharge)) {
                        // $total_fee = $data['total_fee'] * 99 / 10000;
                        // $total_fee = $data['pay_amount'] * 99 / 10000;
                    // $total_fee = $userCharge->amount * 99 / 100;
                    if ($userCharge->charge_state == UserCharge::CHARGE_STATE_WAIT) {
                        $user = User::findOne($userCharge->user_id);
                        $user->account += $userCharge->amount;
                        if ($user->save()) {
                            $userCharge->charge_state = UserCharge::CHARGE_STATE_PASS;
                        }
                    }
                    $userCharge->update();
                }
                echo 'success';die;
            }
        }
        echo 'fail';die;
    }

    //微信token验证
    public function actionWxcode()
    {
        require Yii::getAlias('@vendor/wx/WxTemplate.php');
        $wxTemplate = new \WxTemplate();
        if (($access_token = session('WxAccessToken')) == null) {
            $access_token = $wxTemplate->getAccessToken();
            session('WxAccessToken', $access_token, 7200);
        }
        tes($access_token);
        $url = 'https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=' . $access_token;
        $data = ['action_name' => 'QR_LIMIT_SCENE', 'action_info' => ['scene' => ['scene_id' => '100000']]];
        $json = json_encode($data);

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $result = curl_exec($ch);
        if (curl_errno($ch)) {
            curl_close($ch);
            test($ch);
        } else {
            curl_close($ch);
            $object = json_decode($result);
            $qcode = 'https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=' . $object->ticket;
            test($qcode);
        }
        // $result = Curl::post($url, $json, ['CURLOPT_SSL_VERIFYPEER' => false, 'CURLOPT_SSL_VERIFYHOST' => false, 'CURLOPT_USERAGENT' => 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)', 'CURLOPT_FOLLOWLOCATION' => 1, 'CURLOPT_AUTOREFERER' => 1, 'CURLOPT_RETURNTRANSFER' => true]);
        test($qcode);
    }     

    //微信token验证
    public function actionTest()
    {
        $url = 'http://www.beinengxt.cn';
        $data = Curl::get($url);
        test($data);
        // u()->logout(false);
        session('WxAccessToken', null);
        session('WxUrlCode_' . u()->id, null);
        test('GET:', $_GET, 'POST:', $_POST);
    } 

    public function actionZynotify() //中云支付回调
    {
        $data = $_GET;
        if (isset($data['returncode']) && $data['returncode'] == '00') {
            $return = [
                "memberid" => $data["memberid"], // 商户ID
                "orderid" =>  $data["orderid"], // 订单号
                "amount" =>  $data["amount"], // 交易金额
                "datetime" =>  $data["datetime"], // 交易时间
                "returncode" => $data["returncode"]
            ];
            ksort($return);
            reset($return);
            $string = '';
            foreach($return as $key => $v) {
                $string .= "{$key}=>{$v}&";
            }
            $string .= "key=" . ZYPAY_KEY;
            $newSign = strtoupper(md5($string));
            if ($data['sign'] == $newSign) {
                $userCharge = UserCharge::find()->where('trade_no = :trade_no', [':trade_no' => $data['orderid']])->one();
                //有这笔订单
                if (!empty($userCharge)) {
                    $tradeAmount = $data['amount'];
                    if ($userCharge->charge_state == UserCharge::CHARGE_STATE_WAIT) {
                        $user = User::findOne($userCharge->user_id);
                        $user->account += $tradeAmount;
                        if ($user->save()) {
                            $userCharge->charge_state = UserCharge::CHARGE_STATE_PASS;
                        }
                    }
                    $userCharge->update();
                }
                exit('ok');
            }
        }
        exit('fail');
    }

    public function actionPinganNotify()
    {
        $Data = file_get_contents("php://input");
        $params = explode("&", $Data);
        foreach($params as $key=>$val) {
            $value = explode("=", $val);
            $key = $value[0];
            $resultarr[$key] = $value[1];
        }
        @file_put_contents("./pay.log", json_encode($resultarr)."\r\n", FILE_APPEND);
        $sign = $resultarr['sign'];
        unset($resultarr['sign']);
        $resultarr['trade_result'] = urldecode($resultarr['trade_result']);
        $signature = array();
        foreach($resultarr as $key=>$value){
            $signature[$key]=$key.'='.$value;
        }
        $signature['open_key']='open_key'.'='.PINGAN_OPEN_KEY;
        ksort($signature);
        #先sha1加密 在md5加密
        $sign_str = md5(sha1(implode('&', $signature)));
        $total_fee = number_format($resultarr['amount']/100.0, 2, ".", "");
        if($sign_str == $sign) {
            $trade_no = $resultarr['out_no'];
            // 支付成功
            $userCharge = UserCharge::find()->where('trade_no = :trade_no', [':trade_no'=> $trade_no])->one();
            if (!empty($userCharge)) {
                if ($userCharge->charge_state == UserCharge::CHARGE_STATE_WAIT) {
                    $user = User::findOne($userCharge->user_id);
                    $user->account += $total_fee;
                    if ($user->save()) {
                        $userCharge->charge_state = UserCharge::CHARGE_STATE_PASS;
                    }
                }
                $userCharge->update();
                @file_put_contents("./pay.log", "SUCCESS\r\n", FILE_APPEND);
                exit("notify_success");
            }
        }else {
            @file_put_contents("./pay.log", "MD5ERR\r\n", FILE_APPEND);
            exit("MD5ERR");
        }
    }

    /**
    * @authname  投资学院页面
    */
    public function actionInvestment()
    {
        return $this->render('investment');
    }

    //每五分钟更新账户异常
    public function actionUpdateUser()
    {
        $bool = self::db('UPDATE `user` SET blocked_account= 0 WHERE blocked_account < 0')->queryAll();
        test($bool);
    }

    //每天凌晨5点清除昨天的数据
    public function actionNqdelete()
    {
        $time = date('Y-m-d 0:10:00', time());
        self::db('DELETE FROM data_eurjap WHERE time < "'.$time.'"')->query();
        self::db('DELETE FROM data_gbpjap WHERE time < "'.$time.'"')->query();
        self::db('DELETE FROM data_longyanxiang WHERE time < "'.$time.'"')->query();
        self::db('DELETE FROM data_usajap WHERE time < "'.$time.'"')->query();

        return l('每天凌晨5点清除昨天的数据');
    } 

    public function actionHmAlipaynotify() //海马支付回调
    {
        require Yii::getAlias('@vendor/hm/HaimaPayment.php');
        $haiMa = new \ApiClient();
        $haiMa->appId = HM_APPID;
        $haiMa->secret = HM_APPSECRET;
        $data = $_POST;
        $resSign = $haiMa->requestSignVerify($data);
        if($resSign) {
            $userCharge = UserCharge::find()->where('trade_no = :trade_no', [':trade_no' => $data['out_trade_no']])->one();
            //有这笔订单
            if (!empty($userCharge)) {
                $amount = $data['total_amount'];
                if ($userCharge->charge_state == UserCharge::CHARGE_STATE_WAIT) {
                    $user = User::findOne($userCharge->user_id);
                    $user->account += $amount;
                    if ($user->save()) {
                        $userCharge->charge_state = UserCharge::CHARGE_STATE_PASS;
                    }
                }
                $userCharge->update();
            }
            exit('SUCCESS');
        }
        exit('fail');
    }

    public function actionAiteNotify()
    {
        $ReturnArray = array( // 返回字段
            "mch_id" => $_REQUEST["mch_id"], // 商户ID
            "out_trade_no" =>  $_REQUEST["out_trade_no"], // 订单号
            "total_fee" =>  $_REQUEST["total_fee"], // 交易金额
            "trade_state" => $_REQUEST["trade_state"],
            "sign" => $_REQUEST["sign"],
        );
        ksort($ReturnArray);
        reset($ReturnArray);
        $md5str = "";
        foreach ($ReturnArray as $key => $val) {
            $md5str = $md5str . $key . "=" . $val . "&";
        }
        $sign = strtoupper(md5($md5str . "key=" . AITE_MD5_KEY));
        @file_put_contents("./pay.log", "Aite Notify: " . json_encode($_REQUEST) . "\r\n", FILE_APPEND);
        if ($sign == $_REQUEST["sign"]) {
            $trade_no = $_REQUEST["out_trade_no"];
            $userCharge = UserCharge::find()->where('trade_no = :trade_no', [':trade_no'=> $trade_no])->one();
            if (!empty($userCharge)) {
                if ($userCharge->charge_state == UserCharge::CHARGE_STATE_WAIT) {
                    $db = Yii::$app->db;
                    $transaction = $db->beginTransaction();
                    try{
                        $user = User::findOne($userCharge->user_id);
                        $user->account += $userCharge->score;
                        $res = $user->save();
                        $_where = [
                            "trade_no" => $trade_no,
                            "charge_state" => UserCharge::CHARGE_STATE_WAIT
                        ];
                        $res1 = UserCharge::updateAll(['charge_state' => UserCharge::CHARGE_STATE_PASS], $_where);
                        if($res && $res1){
                            @file_put_contents("./pay.log", "success\r\n", FILE_APPEND);
                            //cache($trade_no, null);
                            $transaction->commit();//提交事务会真正的执行数据库操作
                            exit("SUCCESS");
                        }else{
                            @file_put_contents("./pay.log", "failed_". $res . "_" . $res1 ."\r\n", FILE_APPEND);
                            $transaction->rollback();//如果操作失败, 数据回滚
                            exit("ERROR");
                        }
                    }catch (\Exception $e) {
                        @file_put_contents("./pay.log", "failed_" . $e->getMessage() . "\r\n", FILE_APPEND);
                        $transaction->rollback();//如果操作失败, 数据回滚
                        exit("ERROR");
                    }
                }
            }
        }else{
            exit("SIGN ERROR");
        }
    }

    public function actionYifuNotify() //易付通回调
    {
        $input = file_get_contents('php://input');
        parse_str($input, $request);
        require Yii::getAlias('@vendor/yifu/yifuPay.php');
        $yifuPay = new \yifuPay();
        $check = $yifuPay->validate_sign($request['out_trade_no'], $request['time_end'], $request['sign']);
        if($check){
            @file_put_contents("./pay.log", json_encode($request)."\r\n", FILE_APPEND);
            $trade_no = $request['out_trade_no'];
            $userCharge = UserCharge::find()->where('trade_no = :trade_no', [':trade_no'=> $trade_no])->one();
            if (!empty($userCharge)) {
                if ($userCharge->charge_state == UserCharge::CHARGE_STATE_WAIT) {
                    $db = Yii::$app->db;
                    $transaction = $db->beginTransaction();
                    try{
                        $user = User::findOne($userCharge->user_id);
                        $user->account += $userCharge->score;
                        $res = $user->save();
                        $_where = [
                            "trade_no" => $trade_no,
                            "charge_state" => UserCharge::CHARGE_STATE_WAIT
                        ];
                        $res1 = UserCharge::updateAll(['charge_state' => UserCharge::CHARGE_STATE_PASS], $_where);
                        if($res && $res1){
                            @file_put_contents("./pay.log", "success\r\n", FILE_APPEND);
                            //cache($trade_no, null);
                            $transaction->commit();//提交事务会真正的执行数据库操作
                            exit("success");
                            //return true;
                        }else{
                            @file_put_contents("./pay.log", "failed_". $res . "_" . $res1 ."\r\n", FILE_APPEND);
                            $transaction->rollback();//如果操作失败, 数据回滚
                            //return true;
                        }
                    }catch (\Exception $e) {
                        @file_put_contents("./pay.log", "failed_" . $e->getMessage() . "\r\n", FILE_APPEND);
                        $transaction->rollback();//如果操作失败, 数据回滚
                        //return false;
                    }
                }
            }

        }
    }
    public function actionYifunewNotify() //易付通回调
    {
//        $input = file_get_contents('php://input');
//        parse_str($input, $request);
        $request = $_REQUEST;
        require Yii::getAlias('@vendor/yifu/yifuNewPay.php');
        $yifuPay = new \yifuNewPay();
        $check = $yifuPay->validate_sign($request, $request['sign']);
        if($check){
            @file_put_contents("./pay.log", json_encode($request)."\r\n", FILE_APPEND);
            $trade_no = $request['sdorderno'];
            $userCharge = UserCharge::find()->where('trade_no = :trade_no', [':trade_no'=> $trade_no])->one();
            if (!empty($userCharge)) {
                if ($userCharge->charge_state == UserCharge::CHARGE_STATE_WAIT) {
                    $db = Yii::$app->db;
                    $transaction = $db->beginTransaction();
                    try{
                        $user = User::findOne($userCharge->user_id);
                        $user->account += $userCharge->score;
                        $res = $user->save();
                        $_where = [
                            "trade_no" => $trade_no,
                            "charge_state" => UserCharge::CHARGE_STATE_WAIT
                        ];
                        $res1 = UserCharge::updateAll(['charge_state' => UserCharge::CHARGE_STATE_PASS], $_where);
                        if($res && $res1){
                            @file_put_contents("./pay.log", "success\r\n", FILE_APPEND);
                            //cache($trade_no, null);
                            $transaction->commit();//提交事务会真正的执行数据库操作
                            exit("success");
                            //return true;
                        }else{
                            @file_put_contents("./pay.log", "failed_". $res . "_" . $res1 ."\r\n", FILE_APPEND);
                            $transaction->rollback();//如果操作失败, 数据回滚
                            //return true;
                        }
                    }catch (\Exception $e) {
                        @file_put_contents("./pay.log", "failed_" . $e->getMessage() . "\r\n", FILE_APPEND);
                        $transaction->rollback();//如果操作失败, 数据回滚
                        //return false;
                    }
                }
            }
        }
    }

    public function actionHuilongNotify()
    {
        $request = $_POST;
        @file_put_contents("./pay.log", json_encode($request)."\r\n", FILE_APPEND);
        require Yii::getAlias('@vendor/huilong/hlpay.php');
        $hlpay = new \hlpay();
        if($hlpay->validate_sign($request, $request['sign'])){
            if($request["status"] == "200" && $request["orderStatus"] == "SUCCESS"){
                $trade_no = $request['orderNo'];
                $userCharge = UserCharge::find()->where('trade_no = :trade_no', [':trade_no'=> $trade_no])->one();
                if (!empty($userCharge)) {
                    if ($userCharge->charge_state == UserCharge::CHARGE_STATE_WAIT) {
                        $db = Yii::$app->db;
                        $transaction = $db->beginTransaction();
                        try{
                            $user = User::findOne($userCharge->user_id);
                            $user->account += $userCharge->score;
                            $res = $user->save();
                            $_where = [
                                "trade_no" => $trade_no,
                                "charge_state" => UserCharge::CHARGE_STATE_WAIT
                            ];
                            $res1 = UserCharge::updateAll(['charge_state' => UserCharge::CHARGE_STATE_PASS], $_where);
                            if($res && $res1){
                                @file_put_contents("./pay.log", "success\r\n", FILE_APPEND);
                                //cache($trade_no, null);
                                $transaction->commit();//提交事务会真正的执行数据库操作
                                exit("SUCCESS");
                                //return true;
                            }else{
                                @file_put_contents("./pay.log", "failed_". $res . "_" . $res1 ."\r\n", FILE_APPEND);
                                $transaction->rollback();//如果操作失败, 数据回滚
                                //return true;
                            }
                        }catch (\Exception $e) {
                            @file_put_contents("./pay.log", "failed_" . $e->getMessage() . "\r\n", FILE_APPEND);
                            $transaction->rollback();//如果操作失败, 数据回滚
                            //return false;
                        }
                    }
                }
            }
        }else{
            @file_put_contents("./pay.log", "Sign error\r\n", FILE_APPEND);
            exit("SIGN ERROR");
        }
    }
}
